#coding: utf-8
from copy import deepcopy

from main.authfuncs import auth_user_required, get_user_profile
from main.views import get_default_context
from django.http import HttpResponse, Http404, HttpResponseServerError

from django.shortcuts import render_to_response
import simplejson as json
from models import Vote
from tmwebapi import tm_token_required, request_token, tm_json_response
from tmwebapi import send_rocks, send_sucks, send_queue_track

from sqlitefuncs import fetchQuery, makeQuery, getSpecInfo, fetchDict, SORT_LIST, QUERY_TEMPLATE
import time, os, sys
from datetime import datetime

def tmradio(request):
    c = get_default_context(request)
    return render_to_response('tmradio.html', c)

@auth_user_required
@tm_token_required

def send_vote(request, **kwargs):
    #profile = get_user_profile(request)
    profile = kwargs['profile']
    try:
        track_id = int(kwargs['track_id'])
        vote = str(kwargs['vote'])
    except Exception as e:
        track_id, vote = None, None

    if not track_id:
        return tm_json_response(status='error', message='Wrong track id.')
    if not vote in ('rocks', 'sucks', ):
        return tm_json_response(status='error', message='Wrong vote.')

    if True: #try:
        v = Vote(user = profile.user, track_id = track_id, vote = 1 if vote=='rocks' else 0)
        if v.save():
            if vote == 'rocks':
                result = send_rocks(profile.tm_token, track_id)
            else:
                result = send_sucks(profile.tm_token, track_id)

            if result['status'] == 'ok':
                # response message example: OK, current weight of track #5921 is 1.2500.
                if "OK, current weight of track" in result['message']:
                    result['message'] = u"Голос принят. Новый рейтинг "+result['message'].split()[-1]
            return tm_json_response(**result)
        else:
            return tm_json_response(status="error", message=u"Вы уже проголосовали!")
    else: #except Exception as e:
        return tm_json_response(status="error", message="Ошибка на сервере. "+e)

@auth_user_required
def request_tm_token(request, *args, **kwargs):
    aid_type, user_aid = kwargs.get("aid_type", None), None
    if aid_type == 'email' and request.user.email: user_aid = request.user.email
    if aid_type == 'jid' and kwargs['profile'].jabber: user_aid = kwargs['profile'].jabber
    if aid_type and user_aid:
        # You'll soon receive a message with a confirmation link.
        result = request_token(user_aid, aid_type)
        if result and result['status'] == 'ok':
            result['message'] = u'Скоро Вы получите сообщение с дальнейшими инструкциями. ' + \
                                u'Полученный токен нужно будет ввести в Ваш профиль.'
        return tm_json_response(**result)

    else:
        return tm_json_response(status="error", message=u"Wrong data for authorization. t{0} u{1}".format(aid_type, user_aid))

def tmsearch(request):
    c = get_default_context(request)
    if not request.method == 'GET' or not request.GET.get('ajax', None):
        c['sortList'] = SORT_LIST
        c['DBDate'] = datetime.fromtimestamp(os.stat('/srv/tmradioweb/tmradio/ardj.sqlite')[8])
        query_r = fetchQuery("SELECT label, COUNT(track_id) AS tc FROM labels WHERE NOT label LIKE '%%:%%' GROUP BY label ORDER BY tc DESC LIMIT 20")
        c['labels'] = sorted([one[0] for one in query_r or []])
        query_r = fetchQuery("SELECT DISTINCT label FROM labels WHERE NOT label LIKE '%%:%%'")
        c['allLabels'] = sorted([one[0] for one in query_r or [] if one[0]])
        c['tracksCount'] = fetchQuery("SELECT COUNT(*) FROM tracks WHERE weight>0")[0][0]
        c['setSearchData'] = ''
        if request.GET.get('permalink', True):
            data = json.dumps( getSearchData(request.GET) )
            c['setSearchData'] = u"""
                var searchDataSet = $.parseJSON('%s');
                showInfo(searchDataSet);
            """%data
        return render_to_response('tmsearch/search.html', c)
    else:
        data = getSearchData(request.GET)
        jsonData = json.dumps(data)
        return HttpResponse(jsonData)


def getSearchData(params):
    if params.get('spec', False): return getSpecInfo(params.get('spec'))
    elif params.get('name', False) or params.get('labelFilter', False) or params.get('vocals', False) or params.get('bookmarkId', False):
        s_params = {}
        if params.get('name', False): s_params['name'] = params.get('name')
        if params.get('order', False): s_params['order'] = params.get('order')
        if params.get('orderDir', False): s_params['orderDir'] = params.get('orderDir')
        if params.get('limit', False): s_params['limit'] = params.get('limit')
        
        labels = []
        if params.get('labelFilter', False):
            labels+=params.get('labelFilter').strip().split(' ')
        if params.get('vocals', False):
            vocals = params.get('vocals')
            if vocals == 'male': labels+=['male', '-female']
            elif vocals == 'female': labels+=['female', '-male']
            elif vocals == 'both': labels+=['male', 'female']
            elif vocals == 'instrumental': labels+=['instrumental']
        if params.get('bookmarkId', False): 
            labels += ["bm:"+params.get('bookmarkId')]
        if params.get('lang', False):
            lang = params.get('lang')
            if lang == 'ru': labels+=['lang:ru']
            elif lang == 'en': labels+=['lang:en']
            elif lang == 'other': labels+=['-lang:ru', '-lang:en', '-instrumental']
        if len(labels): s_params['labels'] = labels
        data = search(**s_params)
        data['arguments'] = s_params
        return data

def search(**kwargs):
    print "search {0}".format(kwargs)
    params = kwargs
    if not kwargs.has_key('fieldsString'): fieldsString = 'id, count, artist, title, weight, tagslist'
    else: fieldsString = kwargs['fieldsString']
    params['fieldsString'] = fieldsString
    query = makeQuery(QUERY_TEMPLATE, **params)
    print "search query: ", query.encode('utf-8')
    query_r = fetchQuery(query)
    if query_r and len(query_r): print "found", len(query_r), "results"
    data = fetchDict(fieldsString, query_r)
    result = {'fields': fieldsString.replace(' ','').split(','), 'data': data}
    return result

def queue_track(request, **kwargs):
    token = ''
    profile = get_user_profile(request)
    if profile and profile.tm_token: token = profile.tm_token
    q = send_queue_track(token, kwargs.get('track_id', None))
    return HttpResponse(q)